
//NOWPLAYING.JS
//shows the songs of a playlist
// Author: Wilco

function nowplayingPage() {}
nowplayingPage.prototype.constructor = nowplayingPage;
nowplayingPage.prototype =
{
    templateData: '',
	nowplayingJSON: '',
    nowplayingData: null,
	playlistJSON: '',
	playlistData: {},
	pageTmpl: null,
	albumArtTmpl: null,
	playlistViewTmpl: null,
	updateTimer: null,
	lastUpdateTime: 0,
	trackChangeTimer: null,
	seekDragObject: null,
	volumeDragObject: null,
	albumArtRequest: null,
	albumArtRequestURL: '',
    loadPage: function()
    {
        this.onOutput = function(title,pageTemplate) { ProcessFullPageOutput(title,pageTemplate); }
        this.loadDefaults();
        //Load template data
        LoadFile(SkinDir + 'nowplaying.html', this.onLoadTemplate.bind(this));
		LoadScript(SkinDir + 'nowplaying.css', 'css');
    },
    loadDefaults: function()
    {  
            
        AddDefaultPageData("nowplaying",{
                "view": 'albumArt',
            });
    },
    onLoadTemplate: function(response)
    {
        this.templateData = response;
        this.loadData();
    },
    loadData: function()
    {
        //Load player data
        var url = ServiceDir + 'player';
        LoadFile(url, this.onLoadData.bind(this));
    },
	loadAlbumArt: function()
	{
		if (this.albumArtRequest != null)
			return;
		
		this.albumArtRequestURL = ServiceDir + 'player/art?rand=' + parseInt(Math.random() * 10000);
		this.albumArtRequest =	
			$.ajax(
			{
			url: this.albumArtRequestURL,
			type: 'GET',
			error: function(t) 
			{ document.getElementById('albumArtImg').style.display ='none'; gCurrentPage.albumArtRequest = null; },
			success: function(t) 
			{	var img =document.getElementById('albumArtImg');
				img.src = gCurrentPage.albumArtRequestURL;
				img.style.display = 'block';
				gCurrentPage.albumArtRequest = null;	},
		});
	},
    onLoadData: function(response)
    {  
       this.generateOutput();
	   this.onUpdateData(response);
    },
	onUpdateData: function(response)
	{
       this.nowplayingJSON = response;
        try
        {    
			var newData = eval("(" + this.nowplayingJSON + ")");
		}
        catch (e)
        {    showError('Cannot understand service data'); return; }
		//Update album art if required
		if (newData.curItem != null)
		{
			if (this.nowplayingData && this.nowplayingData.curItem != null)
			{
				if (newData.curItem.guid != this.nowplayingData.curItem.guid)
					this.loadAlbumArt();
			}
			else
				this.loadAlbumArt();
		}
		this.nowplayingData = newData;
		this.lastUpdateTime = (new Date()).getTime();
		this.updateUI();
	},
    updateUI: function()
    {
        if (gTelescope)
            this.updateUIForTelescope();
        else
            this.updateUIForWings();
    },
	updateUIForTelescope: function()
	{	//Updates UI on new data retrieval
		if (!this.volumeDragObject || !this.volumeDragObject.IsDragging())
		{
			var volume = this.nowplayingData.muted == true ? 0 : this.nowplayingData.volume;
			document.getElementById('volumeThumbImg').style.left = parseInt(this.nowplayingData.volume * document.getElementById('volumeBar').offsetWidth) + 'px';
		}

		
		switch(this.nowplayingData.repeatMode)
		{	case 0:
			document.getElementById('repeatModeImg').src = 'button_repeat_none.png';
			break;
			case 1:
			document.getElementById('repeatModeImg').src = 'button_repeat_one.png';
			break;
			case 2:
			document.getElementById('repeatModeImg').src = 'button_repeat_all.png';
			break;
		}
		switch(this.nowplayingData.mode)
		{	case 0:
			case 1:
			document.getElementById('modeImg').src = 'button_shuffle_off.png';
			break;
			default:
			document.getElementById('modeImg').src = 'button_shuffle_on.png';
			break;
		}
				
		if (this.nowplayingData.curItem == null)
		{	//Nothing playing
			document.getElementById('nowplaying_artist').innerHTML = '&nbsp;';
			document.getElementById('nowplaying_title').innerHTML = 'Nothing Playing';
			document.getElementById('nowplaying_album').innerHTML = '&nbsp;';
			document.getElementById('seekDuration').innerHTML = this.timeToMinuteString(0);
			document.getElementById('seekPosition').innerHTML = this.timeToMinuteString(1);
			//TODO: show disabled play button image
			return;
		}
		//Everything past here requires a track to be being played	
		document.getElementById('nowplaying_artist').innerHTML = this.nowplayingData.curItem.artist;
		document.getElementById('nowplaying_title').innerHTML = this.nowplayingData.curItem.name;
		document.getElementById('nowplaying_album').innerHTML = this.nowplayingData.curItem.album;
		document.getElementById('seekDuration').innerHTML = this.timeToMinuteString(this.nowplayingData.duration);
		
		this.updateSeekBarWithTime();
		if (this.nowplayingData.status == 1 || this.nowplayingData.status == 8)
		{
			this.setUpdateTimer();	
			var delay = 1000;
			
			if (this.nowplayingData.status == 1)
				//If not buffering then play like this
				var delay = this.nowplayingData.duration - this.nowplayingData.position;
			
			if (delay > 10000)
				delay = 10000;

			this.setTrackChangeTimer(delay);
			document.getElementById('playPauseButtonImg').src = 'button_pause.png';
		}
		else
		{
			this.clearUpdateTimer();
			document.getElementById('playPauseButtonImg').src = 'button_play.png';
		}
		try
		{
			var playlistView = document.getElementById('playlistView');
			for(var i=0;i<playlistView.childElementCount;i++)
			{
				playlistView.children[i].className = (i == this.nowplayingData.curItemIndex) ? 'playing' : '';
			}
		} catch(e) {}
		
	},
	updateUIForWings: function()
    {
    },
    updateSeekBarWithTime: function()
	{
		var now = (new Date()).getTime();
		var timeSinceUpdate = now - this.lastUpdateTime;
		var position = this.nowplayingData.position + timeSinceUpdate;
		var percentComplete = (position / this.nowplayingData.duration);
		if (!this.seekDragObject || !this.seekDragObject.IsDragging())
		{
			document.getElementById('seekThumbImg').style.left = parseInt(percentComplete * document.getElementById('seekBar').offsetWidth) + 'px';
		}
		document.getElementById('seekPosition').innerHTML = this.timeToMinuteString(position);
	},
	resizeUI: function()
	{
		var width = window.innerWidth;
		var height = window.innerHeight; 
		document.getElementById('albumArtBox').style.height = height - document.getElementById('titlegroup').offsetHeight - document.getElementById('controlsBar').offsetHeight;
		document.getElementById('controlsBox').style.top = height - document.getElementById('controlsBox').offsetHeight;
		document.getElementById('playlistView').style.height = height - document.getElementById('titlegroup').offsetHeight - document.getElementById('controlsBar').offsetHeight;
		
	},
	timeToMinuteString: function(time)
	{
		var minutes = Math.floor(time/60000);
		var seconds = Math.round((time - minutes*60000)/1000);
		var str = minutes + ':' + ((seconds < 10) ? '0' + seconds : seconds);
		return str;
	},
    generateOutput: function()
    {
		this.pageTmpl = new Template();
		this.pageTmpl.load(this.templateData);
		
		this.playlistViewTmpl = this.pageTmpl.removeSubTemplate('playlistview');
        this.onOutput('Now Playing',this.pageTmpl);
		
		var seekBar = document.getElementById('seekBar');
		var seekElement = document.getElementById('seekThumbImg');
		this.seekDragObject = new dragObject("seekThumbImg", null, new Position2D(0,0),
										new Position2D(seekBar.offsetWidth,0), this.grabSeekButton.bind(this), null, this.releaseSeekButton.bind(this), false);
		
	
		var volumeBar = document.getElementById('volumeBar');
		var volumeElement = document.getElementById('volumeThumbImg');
		this.volumeDragObject = new dragObject("volumeThumbImg", null, new Position2D(0,0),
										new Position2D(volumeBar.offsetWidth,0), this.grabVolumeButton.bind(this), null, this.releaseVolumeButton.bind(this), false);
		
	
		this.generateView();
		this.resizeUI();
		$(window).bind('resize',this.resizeUI);
    },
	generateView: function()
	{
		if(gPageData['nowplaying']['view'] == 'playlist')
		{
			
			LoadFile(ServiceDir + 'player/playlist', this.onLoadPlaylist.bind(this));
		}else
		{
			document.getElementById('albumArtBox').style.display = 'block';
			document.getElementById('playlistView').style.display = 'none';
			document.getElementById('volumeBar').style.display = 'block';
			document.getElementById('viewToggleButton').innerHTML = 'List';
		}
	},
	onLoadPlaylist: function(response)
	{
	
       this.playlistJSON = response;
        try
        {    this.playlistData = eval("(" + this.playlistJSON + ")"); }
        catch (e)
        {    showError('Cannot understand service data'); return; }
		
		if (gPageData['nowplaying']['view'] == 'playlist')
			this.showPlaylist();
	},
	showPlaylist: function()
	{
		var viewTmpl = this.playlistViewTmpl.clone();
		var itemtmpl = viewTmpl.removeSubTemplate('item');
        var items = [];
        var newtmpl = null;
		var className;
		for(var i=0;i<this.playlistData.length;i++)
		{
			className = (i == this.nowplayingData.curItemIndex) ? 'playing' : '';
			
            newtmpl = itemtmpl.clone();
            newtmpl.addData({    name: this.playlistData[i].name,
								'item_class': className,
								index: 		i,
                        });
            items.push(newtmpl);
		}
		viewTmpl.addSubTemplate('item',items);
		document.getElementById('playlistView').innerHTML = viewTmpl.parse();
			document.getElementById('albumArtBox').style.display = 'none';
			document.getElementById('playlistView').style.display = 'block';
			document.getElementById('volumeBar').style.display = 'none';
			document.getElementById('viewToggleButton').innerHTML = 'Art';
	},
	setUpdateTimer: function()
	{
		if (this.updateTimer != null) this.clearUpdateTimer();
		this.updateTimer = setInterval(this.onUpdateTimer.bind(this),200);
	},
	clearUpdateTimer: function()
	{
		if (this.updateTimer != null)
		{
			clearInterval(this.updateTimer);
			this.updateTimer = null;
		}
	},
	onUpdateTimer: function()
	{
		this.updateSeekBarWithTime();
	},
	setTrackChangeTimer: function(delay)
	{
		if (this.trackChangeTimer != null) this.clearTrackChangeTimer();
		this.trackChangeTimer = window.setTimeout(this.onTrackChange.bind(this),delay);
	},
	clearTrackChangeTimer: function()
	{
		if (this.trackChangeTimer != null)
		{
			window.clearTimeout(this.trackChangeTimer);
			this.trackChangeTimer = null;
		}
	},
	onTrackChange: function()
	{	this.updateData();	},
	updateData: function()
	{	//Reload Data
        var url = ServiceDir + 'player';
        LoadFile(url, this.onUpdateData.bind(this));
	},
	grabSeekButton: function(eventObj)
	{
	},
	releaseSeekButton: function()
	{
		if (this.nowplayingData.curItemIndex == -1) return;
		
		var seekBar = document.getElementById('seekBar');
		var seekElement = document.getElementById('seekThumbImg');
		var percentage = parseInt(seekElement.style.left) / seekBar.offsetWidth;
		var newPos = parseInt(percentage * this.nowplayingData.duration);
		var url = ServiceDir + 'player';
		$.ajax(
		{
			url: url,
			type: 'POST',
			data: { 'action': 'seek', 'position': newPos},
			error: function(t) 
			{ 
				showError('Error seeking: ' + t.responseText); 
				gCurrentPage.updateData();
			},
			success: function(r) 
			{
				gCurrentPage.updateData();
			}
		});
		//Clear update on the seek button until we update
		this.clearUpdateTimer();
	},
	grabVolumeButton: function()
	{	},
	releaseVolumeButton: function()
	{
		
		var volumeBar = document.getElementById('volumeBar');
		var volumeElement = document.getElementById('volumeThumbImg');
		var newPos = parseInt(volumeElement.style.left) / volumeBar.offsetWidth;
		var url = ServiceDir + 'player';
		$.ajax(
		{
			url: url,
			type: 'POST',
			data: { 'action': 'volume', 'volume': newPos, 'muted' : false},
			error: function(t) 
			{ 
				showError('Error changing volume: ' + t.responseText); 
				gCurrentPage.updateData();
			},
			success: function(t) 
			{
				gCurrentPage.updateData();
			}
		});
	},
    onOutput: function(){},
	unloadPage: function()
	{
		this.clearUpdateTimer();
		this.clearTrackChangeTimer();
	}
}

function PlayPause()
{
	//TODO: make this POST
	var action = 'play';
	if (gCurrentPage.nowplayingData.status == 1)
		var action = 'pause';
		
	var url = ServiceDir + 'player';

	$.ajax(
		{
			url: url,
			type: 'POST',
			data: { 'action': action},
			error: function(t) 
			{ 
				showError('Error playing media: ' + t.responseText); 
			},
			success: function(t) 
			{
				gCurrentPage.updateData();
			}
		});
}

function Next()
{
	var url = ServiceDir + 'player';

	$.ajax({
			url: url,
			type: 'POST',
			data: { 'action': 'next'},
			error: function(t) 
			{ 	showError('Error playing media: ' + t.responseText); },
			success: function(t) 
			{	gCurrentPage.updateData();	}
		});
}
function Previous()
{
	var url = ServiceDir + 'player';

	$.ajax({
			url: url,
			type: 'POST',
			data: { 'action': 'previous'},
			error: function(t) 
			{ 	showError('Error playing media: ' + t.responseText); },
			success: function(t) 
			{	gCurrentPage.updateData();	}
		});
}
function ToggleMode()
{
	var url = ServiceDir + 'player';
	var curMode = gCurrentPage.nowplayingData.mode;
	var newMode = 0;
	switch(curMode)
	{	case 0:	//Forward, go to shuffle
		case 1:
			newMode = 2;
			break;
		default:	//Custom, go to forward
			newMode = 0;
			break;
	}
	
	$.ajax({
			url: url,
			type: 'POST',
			data: { 'action': 'mode', 'mode': newMode},
			error: function(t) 
			{ 	showError('Error playing media: ' + t.responseText); },
			success: function(t) 
			{	gCurrentPage.updateData();	}
		});
}

function ToggleRepeatMode()
{
	var url = ServiceDir + 'player';
	var curMode = gCurrentPage.nowplayingData.repeatMode;
	var newMode = 0;
	switch(curMode)
	{	case 0:	//None, go to all
			newMode = 2;
			break;
		case 1:	//One, go to none
			newMode = 0;
			break;
		default:	//Other, go to one
			newMode = 1;
			break;
	}
	
	$.ajax({
			url: url,
			type: 'POST',
			data: { 'action': 'repeatMode', 'mode': newMode},
			error: function(t) 
			{ 	showError('Error playing media: ' + t.responseText); },
			success: function(t) 
			{	gCurrentPage.updateData();	}
		});
}

function ToggleView()
{
	if (gPageData['nowplaying']['view'] == 'albumArt')
		gPageData['nowplaying']['view'] = 'playlist';
	else
		gPageData['nowplaying']['view'] = 'albumArt';
		
	gCurrentPage.generateView();
	
	return false;
}

function PlayIndex(index)
{
	//TODO: make this POST
	var action = 'playIndex';
		
	var url = ServiceDir + 'player';
	
	$.ajax(
		{
			url: url,
			type: 'POST',
			data: { 'action': action, 'index': index},
			error: function(t) 
			{ 
				showError('Error playing media: ' + t.responseText); 
			},
			success: function(t) 
			{
				gCurrentPage.updateData();
			}
		});
	return false;
}

gLastScriptLoaded = new nowplayingPage();
gScriptLoaded();